package com.woniuxy.service.impl;

import com.woniuxy.mapper.StudentDao;
import com.woniuxy.mapper.impl.StudentDaoImpl;
import com.woniuxy.entity.Student;
import com.woniuxy.exception.PasswordIncorrectException;
import com.woniuxy.exception.UserEmailUsedException;
import com.woniuxy.exception.UserNameUsedException;
import com.woniuxy.service.StudentService;

import java.util.List;

/**
 * @author 作者
 * @create 2025-08-04 15:44
 * 学生业务实现类
 */
public class StudentServiceImpl implements StudentService {
    //业务层调用数据访问层
    StudentDao studentDao = new StudentDaoImpl();

    @Override
    public List<Student> getAll() {
        return studentDao.selectAll();
    }

    @Override
    public void regist(Student student) {
        //检查用户名是否被使用过，没有使用过的才能添加
        Student findStudent = studentDao.selectBySname(student.getSname());
        if (findStudent!=null) {
            throw new UserNameUsedException("用户名被使用");
        }
        //检查邮箱是否被使用过，没有使用过的才能添加
        findStudent = studentDao.selectByEmail(student.getEmail());
        if (findStudent!=null) {
            throw new UserEmailUsedException("用户邮箱被使用");
        }
        int sid = studentDao.selectMaxSid();
        student.setSid(sid+1);
        studentDao.insert(student);
    }

    @Override
    public Student login(String uname, String password) {
        Student student = studentDao.selectBySname(uname);
        if(student==null){
            throw new UserNameUsedException("用户名不存在");
        }
        if(!password.equals(student.getPassword())){
            throw new PasswordIncorrectException("密码错误");
        }
        return student;
    }

    @Override
    public void remove(String sname) {
        if (studentDao.selectBySname(sname)!=null) {
            //查询所有学生，存入集合(dao)
            List<Student> students = studentDao.selectAll();
            //从集合中删除学生
            for(int i=0; i<students.size(); i++){
                if(students.get(i).getSname().equals(sname)){
                    students.remove(i);
                    break;
                }
            }
            //集合的数据，写入文件（覆盖）--dao
            studentDao.saveAll(students);
        }
    }
}
